package weaver.interfaces.avic;

import net.qiyuesuo.sdk.SDKClient;
import net.qiyuesuo.sdk.api.CompanySignService;
import net.qiyuesuo.sdk.bean.contract.StamperType;
import net.qiyuesuo.sdk.bean.sign.local.CompanyLocalSignRequest;
import net.qiyuesuo.sdk.bean.sign.local.LocalSignStamper;
import net.qiyuesuo.sdk.bean.sign.local.SignResult;
import net.qiyuesuo.sdk.impl.CompanySignServiceImpl;
import org.apache.axis.encoding.Base64;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocServiceImpl;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;

import java.io.*;
import java.util.*;
import java.util.zip.ZipInputStream;

public class TySignFileUtil extends BaseBean {


    private int createDoc(int userid, String filepath, String rawFileName, int seccategory) {
        writeLog(">>>>>createDoc>>>>>userid=" + userid + ",filepath=" + filepath + ",rawFileName=" + rawFileName);
        byte[] content = new byte[102400];
        content = null;
        try {
            int byteread;
            byte data[] = new byte[1024];
            InputStream inputStream = new FileInputStream(new File(filepath));
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            while ((byteread = inputStream.read(data)) != -1) {
                outputStream.write(data, 0, byteread);
                outputStream.flush();
            }
            content = outputStream.toByteArray();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        writeLog(">>>>>createDoc>>>>>content=" + content);
        int docid = -1;
        DocServiceImpl docService = new DocServiceImpl();
        DocAttachment[] docAttachment = new DocAttachment[1];
        String docsubject = "";
        String keyword = "";
        String filetype = "";
        String filename = "";
        if (rawFileName.lastIndexOf(".") > -1) {
            filetype = rawFileName.substring(rawFileName.lastIndexOf(".") + 1);
            filename = rawFileName.substring(0, rawFileName.lastIndexOf("."));
        }
        writeLog(">>>>>createDoc>>>>>filetype=" + filetype);
        writeLog(">>>>>createDoc>>>>>filename=" + filename);
        try {
            DocAttachment da = new DocAttachment();
            da.setFilename(filename + "." + filetype);
            da.setFilecontent(Base64.encode(content));
            da.setFiletype(filetype);
            da.setImagefilename(filename + "." + filetype);
            da.setIszip(1);
            da.setIsAesEncrype(0);
            da.setAesCode("0");
            da.setIsextfile("1");
            if (filetype.equalsIgnoreCase("doc")) {
                da.setDocfiletype("3");
            } else if (filetype.equalsIgnoreCase("xls")) {
                da.setDocfiletype("4");
            } else if (filetype.equalsIgnoreCase("ppt")) {
                da.setDocfiletype("5");
            } else if (filetype.equalsIgnoreCase("wps")) {
                da.setDocfiletype("6");
            } else if (filetype.equalsIgnoreCase("docx")) {
                da.setDocfiletype("7");
            } else if (filetype.equalsIgnoreCase("xlsx")) {
                da.setDocfiletype("8");
            } else if (filetype.equalsIgnoreCase("pptx")) {
                da.setDocfiletype("9");
            } else {
                da.setDocfiletype("2");
            }
            docAttachment[0] = da;
            docsubject = filename;
            keyword = filename;
            DocInfo doc = new DocInfo();
            //doc.setMaincategory(678);
            //doc.setSubcategory(44);
            doc.setSeccategory(seccategory);
            doc.setDocSubject(docsubject);
            doc.setDoccontent("");
            doc.setKeyword(keyword);
            doc.setAttachments(docAttachment);
            if (!"".equals(userid)) {
                User user = new User(userid);
                docid = docService.createDocByUser(doc, user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        writeLog(">>>>>createDoc>>>>>docid=" + docid);
        return docid;
    }

    public int pdfFileSignSDK(String imagefileid, int userid, int seccategory,String mainid,String tablename) {
        RecordSet rs = new RecordSet();
        writeLog(">>>>pdfFileSignSDK>>>>>imagefileid=" + imagefileid);
        writeLog(">>>>pdfFileSignSDK>>>>>seccategory=" + seccategory);
        writeLog(">>>>pdfFileSignSDK>>>>>mainid=" + mainid);
        writeLog(">>>>pdfFileSignSDK>>>>>tablename=" + tablename);
        String currentDate = DateUtil.getCurrentDate();
        int docid = -1;
        InputStream fileInputSteam = null;
        try {
            rs.executeQuery("select fileRealPath,isZip,imagefilename from imagefile where imagefileid=?", imagefileid);
            rs.next();
            String fileRealPath = Util.null2String(rs.getString("fileRealPath"));
            writeLog(">>>>pdfFileSignSDK>>>>>fileRealPath=" + fileRealPath);
            String isZip = Util.null2String(rs.getString("isZip"));
            writeLog(">>>>pdfFileSignSDK>>>>>isZip=" + isZip);
            String imagefilename = Util.null2String(rs.getString("imagefilename"));
            String filePath = "/opt/weaver/ecology/tempfile/signfile/" + currentDate + "_" + imagefileid + ".pdf";
            writeLog(">>>>pdfFileSignSDK>>>>>filePath=" + filePath);
            File thefile = new File(fileRealPath);
            if ("1".equals(isZip)) {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile));
                if (zin.getNextEntry() != null) {
                    fileInputSteam = new BufferedInputStream(zin);
                } else {
                    fileInputSteam = new BufferedInputStream(new FileInputStream(thefile));
                }
            }
            String url = "http://172.20.80.3:9182";
            String accessKey = "1bL9JbuOwW";
            String accessSecret = "5cNYucRNsp6UasuNRmfdt05YxzEU8b";
            SDKClient sdkClient = new SDKClient(url, accessKey, accessSecret);
            CompanySignService companySignService = new CompanySignServiceImpl(sdkClient);
            OutputStream fileOutputStream = new FileOutputStream(filePath);
            CompanyLocalSignRequest request = new CompanyLocalSignRequest();
            ArrayList<LocalSignStamper> localSignStampers = new ArrayList<LocalSignStamper>();
            List<Map<String, String>> resultList = getCoordinate(mainid,tablename);
            writeLog(">>>>pdfFileSignSDK>>>>>resultList=" + resultList);
            for (Map<String, String> result : resultList){
                LocalSignStamper localSignStamper = new LocalSignStamper();
                localSignStamper.setType(StamperType.SEAL_CORPORATE);
                localSignStamper.setOffsetX(Util.getDoubleValue(result.get("xz")));
                localSignStamper.setOffsetY(Util.getDoubleValue(result.get("yz")));
                localSignStamper.setPage(Util.getIntValue(result.get("ym")));
                localSignStamper.setSealId(Long.parseLong(result.get("yzid")));
                writeLog(">>>>pdfFileSignSDK>>>>>localSignStamper=" + localSignStamper);
                Collections.addAll(localSignStampers, localSignStamper);
            }
            request.setStampers(localSignStampers);
            List<InputStream> signFiles = new ArrayList<InputStream>();
            signFiles.add(fileInputSteam);
            SignResult signResult = companySignService.sign(signFiles, fileOutputStream, request);
            writeLog(">>>>pdfFileSignSDK>>>>>signResult=" + signResult.getContractId());
            docid = createDoc(userid, filePath, imagefilename, seccategory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return docid;
    }

    public List<Map<String, String>> getCoordinate(String mainid,String tablename) {
        RecordSet rs = new RecordSet();
        List<Map<String, String>> mapList = new ArrayList<>();
        rs.executeQuery("select yzid,xz,yz,ym,gzsy from " + tablename + "_dt1 where mainid=?", mainid);
        while (rs.next()){
            Map<String, String> map = new HashMap<>();
            map.put("yzid", Util.null2String(rs.getString("yzid")));
            map.put("xz", Util.null2String(rs.getString("xz")));
            map.put("yz", Util.null2String(rs.getString("yz")));
            map.put("ym", Util.null2String(rs.getString("ym")));
            map.put("gzsy", Util.null2String(rs.getString("gzsy")));
            mapList.add(map);
        }
        return mapList;
    }

    public String getImagefileIdByDocid(String docid) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select imagefileid from docimagefile where docid=?", docid);
        rs.next();
        return Util.null2String(rs.getString("imagefileid"));
    }
}
